package problems.solved;

import java.math.BigInteger;

import problems.Problem;

// Possible without triangle, as all hexagons are triangles
public class Problem45 extends Problem<BigInteger> {
	private static final BigInteger ONE = BigInteger.ONE;
	private static final BigInteger TWO = BigInteger.valueOf(2);
	private static final BigInteger THREE = BigInteger.valueOf(3);

	public static void main(String[] args) {
		Problem45 problem45 = new Problem45();
		problem45.runTimed();
		problem45.printResult();
	}
	
	@Override
	public void run() {
//		long triangleIndex = 287;
		long pentagonIndex = 167;
		long hexagonIndex = 145;
		
//		BigInteger nextTriangle = triangle(triangleIndex++);
		BigInteger nextPentagonal = pentagon(pentagonIndex++);
		BigInteger nextHexagonal = hexagon(hexagonIndex++);
		
		while (true) {
			switch(least(/*nextTriangle, */nextPentagonal, nextHexagonal)) {
//				case 2 : nextTriangle = triangle(triangleIndex++); break;
				case 1 : nextPentagonal = pentagon(pentagonIndex++); break;
				case -1 : nextHexagonal = hexagon(hexagonIndex++); break;
				case 0: setResult(nextHexagonal); return; // 1533776805
			}
		}
	}

	private int least(BigInteger nextPentagonal, BigInteger nextHexagonal) {
		return nextHexagonal.compareTo(nextPentagonal);
	}

//	private int least(BigInteger nextTriangle, BigInteger nextPentagonal, BigInteger nextHexagonal) {
//		if (nextTriangle.equals(nextHexagonal) && nextTriangle.equals(nextPentagonal)) {
//			return 0;
//		}
//		
//		BigInteger min = nextTriangle.compareTo(nextHexagonal) < 0 ? nextTriangle : nextHexagonal;
//		min = min.compareTo(nextPentagonal) < 0 ? min : nextPentagonal;
//		
//		return min == nextTriangle ? 2 : (min == nextPentagonal ? 1 : -1);
//	}
//	
//	private BigInteger triangle(long i) {
//		BigInteger value = BigInteger.valueOf(i);
//		return value.multiply(value.add(ONE)).divide(TWO);
//	}
	
	private BigInteger pentagon(long i) {
		BigInteger value = BigInteger.valueOf(i);
		return value.multiply(THREE.multiply(value).subtract(ONE)).divide(TWO);
	}
	
	private BigInteger hexagon(long i) {
		BigInteger value = BigInteger.valueOf(i);
		return value.multiply(TWO.multiply(value).subtract(ONE));
	}
}
